package Demo4;

import java.util.Arrays;
import java.util.Comparator;

public class Test {
    public static void main(String[] args) {
        Student student = new Student("zhangsan", 10);
        Student student1 = new Student("lisi", 5);
        //年龄的比较，重写了Comparator的compare方法
        CompareAge compareAge = new CompareAge();
        System.out.println(compareAge.compare(student, student1));
        //姓名的比较，重写了Comparator的compare方法
        CompareName compareName = new CompareName();
        System.out.println(compareName.compare(student, student1));
    }
    public static void bubbleSort(Comparable[] comparables) {//按照年龄冒泡排序
        for (int i = 0; i < comparables.length - 1; i++) {
            for (int j = 0; j < comparables.length - i - 1; j++) {
                if (comparables[j].compareTo(comparables[j + 1]) > 0) {
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j + 1];
                    comparables[j + 1] = tmp;
                }
            }
        }
    }
        public static void main2 (String[]args){
            Student[] student = new Student[3];
            student[0] = new Student("zhangsan", 10);
            student[1] = new Student("lisi", 5);
            student[2] = new Student("wangwu", 7);
            System.out.println(Arrays.toString(student));
            //sort会调用compareTo方法进行排序
            //compareTo方法在类中进行了重写
            Arrays.sort(student);
            System.out.println(Arrays.toString(student));
            //bubbleSort
            bubbleSort(student);
        }

        public static void main1 (String[]args){
            Student student = new Student("zhangsan", 10);
            Student student1 = new Student("lisi", 5);
            //System.out.println(student1 > student);           引用类型不让这么比
            //重写compareto方法完成两者年龄的比较
            System.out.println(student.compareTo(student1));
        }

}
class Student implements Comparable<Student>{
    public String name;
    public int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }
}
//比较器
//优点：对类的侵入性不强
class   CompareAge implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}
class CompareName implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}